﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Data;
using System.Configuration;

namespace TRPOP.Common
{
    /// <summary>
    /// 通用操作方法
    /// </summary>
    public class Util
    {

        /// <summary>
        /// 根据指定的路径信息获取物理路径
        /// 1、支持web引用路径，通过 HttpContext.Current.Server.MapPath 获取 strPath 对应的物理路径
        /// 2、支持非web引用路径
        ///    如果AppSettings 有设置有 root_ 开头的路径，则匹配这样的路径 例如  key="root_Image" value="d:\Image"   , strPath的值为 /Image/20140101 ， 则最终取得的值是d:\image\20140101
        ///    如果没有,则判断当前现成所在的应用程序域来获取目录（AppDomain.CurrentDomain.BaseDirectory）
        /// </summary>
        /// <param name="strPath">指定的路径</param>
        /// <returns>绝对路径</returns>
        public static string GetMapPath(string strPath)
        {
            if (System.Web.HttpContext.Current != null)
            {
                if (strPath.StartsWith("~") == false)
                {
                    strPath = "~" + strPath;
                }
                if (strPath.StartsWith("~/") == false && strPath.Length > 1)
                {
                    strPath = "~/" + strPath.Substring(1);
                }
                return System.Web.HttpContext.Current.Server.MapPath(strPath);
            }
            else //非web程序引用
            {
                string strBaseDirectory = string.Empty;

                bool bIsAppSet = false;
                foreach (string key in ConfigurationManager.AppSettings)
                {
                    if (key.ToLower().StartsWith("root_") && strPath.ToLower().StartsWith(key.ToLower().Replace("root_", @"/")))
                    {
                        strBaseDirectory = ConfigurationManager.AppSettings[key];
                        strPath = strPath.Remove(0, key.ToLower().Replace("root_", "/").Length);
                        bIsAppSet = true;
                    }
                }

                if (bIsAppSet == false)
                {
                    strBaseDirectory = AppDomain.CurrentDomain.BaseDirectory;
                }

                strPath = strPath.Replace("~", "");
                strPath = strPath.Replace("//", "/");
                if (strPath.StartsWith("/"))
                    strPath = strPath.TrimStart('/');
                strPath = strPath.Replace(@"/", @"\");

                return System.IO.Path.Combine(strBaseDirectory, strPath);
            }
        }

        /// <summary>
        /// 获得随机验证码,数字和字符的组合
        /// 来源：23456789ABCDEFHKMNPRSTWXYZ
        /// </summary>
        /// <param name="iRandomLength">验证码的长度</param>
        /// <returns></returns>
        static public string GetRandomCode(int iRandomLength)
        {
            string strRtn = string.Empty;

            Random oRandom = new Random();

            char[] ocdChars = "23456789ABCDEFHKMNPRSTWXYZ".ToCharArray();
            for (int i = 0; i < iRandomLength; i++)
            {
                strRtn += ocdChars[oRandom.Next(0, ocdChars.Length)].ToString();
            }

            return strRtn;
        }

        /// <summary>
        /// 获得随机验证码,数字的组合
        /// </summary>
        /// <param name="iRandomLength">验证码的长度</param>
        /// <returns></returns>
        public static string GetRandomStr(int iRandomLength)
        {
            string RandomStr = string.Empty;

            Random Rnd = new Random();

            for (int i = 1; i <= iRandomLength; i++)
            {
                RandomStr += Rnd.Next(0, 9).ToString();
            }

            return RandomStr;
        }

        /// <summary>
        /// 根据字符串生成图片流，背景白色
        /// </summary>
        /// <param name="strCode">验证码内容</param>
        /// <param name="intLength">文字长度</param>
        /// <param name="intHeight">验证码区域高度</param>
        /// <returns></returns>
        public static MemoryStream IdentifyImg(string strCode, int intLength, int intHeight)
        {

            Bitmap bitMapImage = new System.Drawing.Bitmap((int)(intHeight * 0.86) * intLength, intHeight);
            Graphics graphicImage = Graphics.FromImage(bitMapImage);
            graphicImage.Clear(System.Drawing.Color.White);

            //设置画笔的输出模式
            graphicImage.SmoothingMode = SmoothingMode.HighSpeed;
            LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, bitMapImage.Width, bitMapImage.Height), Color.Blue, Color.DarkRed, 0, true);

            Char[] arrChar = strCode.ToCharArray();

            //添加文本字符串            
            for (int i = 0; i < arrChar.Length; i++)
            {
                graphicImage.DrawString(arrChar[i].ToString(), new Font(System.Drawing.FontFamily.GenericSerif, intHeight * 0.75f, FontStyle.Bold | FontStyle.Italic), brush, new Point(i * (int)(intHeight * 0.82), 0));
            }

            Random random = new Random();
            for (int i = 0; i < 100; i++)
            {
                int x = random.Next(bitMapImage.Width);
                int y = random.Next(bitMapImage.Height);
                bitMapImage.SetPixel(x, y, Color.FromArgb(random.Next()));
            }

            //画图片的边框线
            graphicImage.DrawRectangle(new Pen(Color.Silver), 0, 0, bitMapImage.Width - 1, bitMapImage.Height - 1);
            MemoryStream stream = new MemoryStream();
            bitMapImage.Save(stream, ImageFormat.Jpeg);

            //释放占用的资源
            graphicImage.Dispose();
            bitMapImage.Dispose();

            return stream;
        }

        /// <summary>
        /// 根据字符串生成图片流，背景白色，带颜色干扰噪音
        /// </summary>
        /// <param name="strCode">要生成的文字内容</param>
        /// <returns></returns>
        public static MemoryStream IdentifyImg(string strCode)
        {

            int intFontWidth = 16;//单个字体的宽度范围
            int intFontHeight = 22;//单个字体的高度范围            
            Font oftFont = new Font("Arial", 11, FontStyle.Bold);//字体


            int intImageWidth = strCode.Length * intFontWidth;
            int intImageHeight = intFontHeight;

            Random newRandom = new Random();
            Bitmap image = new Bitmap(intImageWidth, intImageHeight);
            Graphics g = Graphics.FromImage(image);
            //生成随机生成器
            Random random = new Random();
            //白色背景
            g.Clear(Color.White);
            //画图片的背景噪音线
            for (int i = 0; i < 10; i++)
            {
                int x1 = random.Next(image.Width);
                int x2 = random.Next(image.Width);
                int y1 = random.Next(image.Height);
                int y2 = random.Next(image.Height);

                g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
            }
            //画图片的前景噪音点
            for (int i = 0; i < 10; i++)
            {
                int x = random.Next(image.Width);
                int y = random.Next(image.Height);

                image.SetPixel(x, y, Color.FromArgb(random.Next()));
            }
            //灰色边框
            g.DrawRectangle(new Pen(Color.LightGray, 1), 0, 0, intImageWidth - 1, (intImageHeight - 1));
            for (int intIndex = 0; intIndex < strCode.Length; intIndex++)
            {
                string strChar = strCode.Substring(intIndex, 1);
                Brush newBrush = new SolidBrush(GetRandomColor());
                Point thePos = new Point(intIndex * intFontWidth + 1 + newRandom.Next(3), 1 + newRandom.Next(3));
                g.DrawString(strChar, oftFont, newBrush, thePos);
            }
            //将生成的图片发回客户端
            MemoryStream ms = new MemoryStream();
            image.Save(ms, ImageFormat.Png);
            g.Dispose();
            image.Dispose();

            return ms;

        }

        /// <summary>
        /// 获得随机颜色
        /// </summary>
        /// <returns></returns>
        public static Color GetRandomColor()
        {
            Random RandomNum_First = new Random((int)DateTime.Now.Ticks);
            System.Threading.Thread.Sleep(RandomNum_First.Next(50));
            Random RandomNum_Sencond = new Random((int)DateTime.Now.Ticks);
            //为了在白色背景上显示，尽量生成深色
            int int_Red = RandomNum_First.Next(256);
            int int_Green = RandomNum_Sencond.Next(256);
            int int_Blue = (int_Red + int_Green > 400) ? 0 : 400 - int_Red - int_Green;
            int_Blue = (int_Blue > 255) ? 255 : int_Blue;
            return Color.FromArgb(int_Red, int_Green, int_Blue);
        }

        /// <summary>
        /// string[] to DataTable
        /// 转换 string[] 到一个table的一列里
        /// </summary>
        /// <param name="ColumnName"></param>
        /// <param name="Array"></param>
        /// <returns></returns>
        public static DataTable Convert(string ColumnName, string[] Array)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add(ColumnName, typeof(string));

            for (int i = 0; i < Array.Length; i++)
            {
                DataRow dr = dt.NewRow();
                dr[ColumnName] = Array[i].ToString();
                dt.Rows.Add(dr);
            }

            return dt;
        }
    }
}
